package com.lsa.letcode.the29.divide;

public class Solution {
	public long divideLong(long dividend, long divisor) {
		if (divisor == 0) {
    		return Integer.MAX_VALUE;
    	}
    	else if (dividend == 0) {
    		return 0;
    	}
		
		long signum = signum(dividend, divisor);
    	if (dividend < 0) {
    		dividend = -dividend;
    	}
    	if (divisor < 0) {
    		divisor = -divisor;
    	}
    	
    	if (dividend < divisor) {
    		return 0;
    	}
    	
    	long res = 1;
    	long acc = divisor;
    	
    	while(dividend >= acc + acc) {
			res += res;
			acc = acc + acc;
		}
		
    	res += divideLong(dividend - acc, divisor);
    	
    	return signum > 0? res : -res;
	}
	
    public int divide(int dividend, int divisor) {
    	long res = divideLong(dividend, divisor);
    	if (res > Integer.MAX_VALUE) {
    		return Integer.MAX_VALUE;
    	}
    	return (int)res;
    }
    
    private long signum(long dividend, long divisor) {
    	if (dividend > 0 && divisor < 0) {
    		return -1;
    	}
    	else if (dividend < 0 && divisor > 0) {
    		return -1;
    	}
		return 1;
	}
}